package fun.hijklmn.magic.admin.server.endpoint;

import fun.hijklmn.magic.common.constants.CharsetConstant;
import fun.hijklmn.magic.common.constants.ContentTypeConstant;
import fun.hijklmn.magic.common.enums.ResponseCodeEnum;
import fun.hijklmn.magic.common.utils.JsonUtil;
import fun.hijklmn.magic.common.utils.ResultVOUtil;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @Author fs
 * @Date 2021/7/1 13:28
 * @Version 0.0.1-SNAPSHOT
 **/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        httpServletResponse.setCharacterEncoding(CharsetConstant.UTF8);
        httpServletResponse.setContentType(ContentTypeConstant.APPLICATION_JSON);

        if (e instanceof LockedException) {
            httpServletResponse.getWriter().println(JsonUtil.toJsonString(ResultVOUtil.parse(ResponseCodeEnum.ACCOUNT_LOCKED, e.getMessage())));
        } else if (e instanceof AccountExpiredException) {
            httpServletResponse.getWriter().println(JsonUtil.toJsonString(ResultVOUtil.parse(ResponseCodeEnum.SESSION_EXPIRED, e.getMessage())));
        } else if (e instanceof UsernameNotFoundException) {
            httpServletResponse.getWriter().println(JsonUtil.toJsonString(ResultVOUtil.parse(ResponseCodeEnum.ERROR, e.getMessage())));
        } else {
            httpServletResponse.getWriter().println(JsonUtil.toJsonString(ResultVOUtil.parse(ResponseCodeEnum.ERROR, "出现异常")));
        }

        httpServletResponse.getWriter().flush();
    }

}
